<template>
  <view class="container">
    <!-- 自定义导航栏 -->
    <u-navbar
      :is-back="false"
      title="预约记录"
      title-color="#ffffff"
      :background="{ background: 'linear-gradient(to right, #1A8DFF, #0269D3)' }"
    ></u-navbar>
    
    <!-- 状态切换 -->
    <view class="tabs-section">
      <u-tabs
        :list="tabsList"
        :is-scroll="false"
        :current="current"
        @change="tabChange"
        active-color="#1A8DFF"
      ></u-tabs>
    </view>
    
    <!-- 预约记录列表 -->
    <view class="record-list">
      <view 
        class="record-item" 
        v-for="(item, index) in recordList" 
        :key="index"
        @click="goToDetail(item.id)"
      >
        <view class="record-header">
          <text class="library-name">{{ item.library_name }}</text>
          <text class="status" :class="'status-' + item.status">{{ getStatusText(item.status) }}</text>
        </view>
        
        <view class="record-info">
          <view class="info-row">
            <text class="label">座位:</text>
            <text class="value">{{ item.seat_name }}</text>
          </view>
          <view class="info-row">
            <text class="label">日期:</text>
            <text class="value">{{ item.reserve_date }}</text>
          </view>
          <view class="info-row">
            <text class="label">时段:</text>
            <text class="value">{{ getTimeSlotText(item.time_slot) }}</text>
          </view>
          <view class="info-row">
            <text class="label">预约号:</text>
            <text class="value">{{ item.reservation_no }}</text>
          </view>
        </view>
        
        <view class="record-footer">
          <text class="time">预约时间: {{ item.create_time }}</text>
          <view class="action-buttons">
            <u-button 
              v-if="item.status === 'waiting'" 
              type="error" 
              size="mini"
              @click.stop="cancelReservation(item.id)"
            >取消预约</u-button>
            <u-button 
              v-if="item.status === 'waiting' || item.status === 'using'" 
              type="primary" 
              size="mini"
              @click.stop="showQrCode(item)"
            >{{ item.status === 'waiting' ? '签到' : '签退' }}</u-button>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 空状态 -->
    <u-empty v-if="recordList.length === 0" mode="list" text="暂无预约记录"></u-empty>
    
    <!-- 加载更多 -->
    <u-loadmore v-if="recordList.length > 0" :status="loadStatus" />
    
    <!-- 签到/签退二维码弹窗 -->
    <u-popup
      v-model="showQrCodePopup"
      mode="center"
      border-radius="10"
      width="80%"
      height="auto"
    >
      <view class="qrcode-popup">
        <view class="popup-title">{{ currentAction === 'checkIn' ? '签到' : '签退' }}二维码</view>
        <view class="qrcode-wrapper">
          <image class="qrcode" :src="qrCodeUrl" mode="aspectFit"></image>
        </view>
        <view class="popup-info">
          <view class="info-item">
            <text class="label">预约号:</text>
            <text class="value">{{ currentReservation.reservation_no }}</text>
          </view>
          <view class="info-item">
            <text class="label">座位:</text>
            <text class="value">{{ currentReservation.seat_name }}</text>
          </view>
          <view class="info-item">
            <text class="label">时间:</text>
            <text class="value">{{ currentReservation.reserve_date }} {{ getTimeSlotText(currentReservation.time_slot) }}</text>
          </view>
        </view>
        <view class="popup-tip">请在图书馆扫码{{ currentAction === 'checkIn' ? '签到' : '签退' }}</view>
        <view class="popup-buttons">
          <u-button @click="showQrCodePopup = false">关闭</u-button>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import { mapGetters } from 'vuex'

export default {
  data() {
    return {
      tabsList: [
        { name: '全部' },
        { name: '待使用' },
        { name: '使用中' },
        { name: '已完成' },
        { name: '已取消' }
      ],
      current: 0,
      recordList: [],
      page: 1,
      size: 10,
      total: 0,
      loadStatus: 'loading', // loading, nomore, loadmore
      statusMap: {
        0: 'all',
        1: 'waiting',
        2: 'using',
        3: 'completed',
        4: 'cancelled'
      },
      showQrCodePopup: false,
      currentReservation: {},
      currentAction: 'checkIn', // checkIn or checkOut
      qrCodeUrl: ''
    }
  },
  computed: {
    ...mapGetters(['userInfo', 'hasLogin'])
  },
  onLoad() {
    // 检查登录状态
    if (!this.hasLogin) {
      this.checkLogin()
    } else {
      this.getReservations()
    }
  },
  onShow() {
    // 如果已登录，刷新数据
    if (this.hasLogin) {
      this.page = 1
      this.recordList = []
      this.getReservations()
    }
  },
  methods: {
    // 切换标签
    tabChange(index) {
      this.current = index
      this.page = 1
      this.recordList = []
      this.getReservations()
    },
    
    // 获取预约记录
    async getReservations() {
      try {
        uni.showLoading({
          title: '加载中'
        })
        
        const status = this.statusMap[this.current]
        
        const res = await this.$api.getReservations({
          page: this.page,
          size: this.size,
          status: status
        })
        
        uni.hideLoading()
        
        if (res.data && res.data.code === 200) {
          const { rows, count } = res.data.data
          
          this.recordList = this.page === 1 ? rows : [...this.recordList, ...rows]
          this.total = count
          
          // 更新加载状态
          if (this.recordList.length >= this.total) {
            this.loadStatus = 'nomore'
          } else {
            this.loadStatus = 'loadmore'
          }
        }
      } catch (error) {
        uni.hideLoading()
        console.error('获取预约记录失败', error)
        uni.showToast({
          title: '获取预约记录失败',
          icon: 'none'
        })
      }
    },
    
    // 获取状态文本
    getStatusText(status) {
      const statusTextMap = {
        'waiting': '待使用',
        'using': '使用中',
        'completed': '已完成',
        'cancelled': '已取消',
        'expired': '已过期'
      }
      return statusTextMap[status] || '未知状态'
    },
    
    // 获取时段文本
    getTimeSlotText(timeSlot) {
      const timeSlotTextMap = {
        'morning': '上午 (8:00-12:00)',
        'afternoon': '下午 (13:00-17:00)',
        'evening': '晚上 (18:00-22:00)',
        'allday': '全天 (8:00-22:00)'
      }
      return timeSlotTextMap[timeSlot] || '未知时段'
    },
    
    // 跳转到详情页
    goToDetail(id) {
      uni.navigateTo({
        url: `/pages/record/detail?id=${id}`
      })
    },
    
    // 取消预约
    cancelReservation(id) {
      uni.showModal({
        title: '提示',
        content: '确定要取消该预约吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              uni.showLoading({
                title: '取消中'
              })
              
              const res = await this.$api.cancelReservation({
                id
              })
              
              uni.hideLoading()
              
              if (res.data && res.data.code === 200) {
                uni.showToast({
                  title: '取消成功',
                  icon: 'success'
                })
                
                // 刷新列表
                this.page = 1
                this.recordList = []
                this.getReservations()
              } else {
                uni.showToast({
                  title: res.data.message || '取消失败',
                  icon: 'none'
                })
              }
            } catch (error) {
              uni.hideLoading()
              console.error('取消预约失败', error)
              uni.showToast({
                title: '取消失败，请稍后重试',
                icon: 'none'
              })
            }
          }
        }
      })
    },
    
    // 显示二维码
    showQrCode(item) {
      this.currentReservation = item
      this.currentAction = item.status === 'waiting' ? 'checkIn' : 'checkOut'
      
      // 生成二维码
      this.qrCodeUrl = `https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${this.currentAction}_${item.id}`
      
      this.showQrCodePopup = true
    },
    
    // 检查登录状态
    checkLogin() {
      if (!this.hasLogin) {
        uni.showModal({
          title: '提示',
          content: '请先登录',
          confirmText: '去登录',
          success: (res) => {
            if (res.confirm) {
              uni.navigateTo({
                url: '/pages/login/login'
              })
            } else {
              uni.switchTab({
                url: '/pages/index/index'
              })
            }
          }
        })
        return false
      }
      return true
    },
    
    // 上拉加载更多
    onReachBottom() {
      if (this.loadStatus === 'nomore') return
      
      this.page++
      this.loadStatus = 'loading'
      this.getReservations()
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 30rpx;
}

.tabs-section {
  background-color: #ffffff;
  margin-bottom: 20rpx;
}

.record-list {
  padding: 0 20rpx;
}

.record-item {
  background-color: #ffffff;
  border-radius: 10rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.record-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
  
  .library-name {
    font-size: 32rpx;
    font-weight: bold;
  }
  
  .status {
    font-size: 26rpx;
    padding: 6rpx 16rpx;
    border-radius: 20rpx;
    
    &.status-waiting {
      background-color: #e6f7ff;
      color: #1890ff;
    }
    
    &.status-using {
      background-color: #f6ffed;
      color: #52c41a;
    }
    
    &.status-completed {
      background-color: #f9f9f9;
      color: #999999;
    }
    
    &.status-cancelled {
      background-color: #fff1f0;
      color: #ff4d4f;
    }
    
    &.status-expired {
      background-color: #fff7e6;
      color: #fa8c16;
    }
  }
}

.record-info {
  padding: 20rpx 0;
}

.info-row {
  display: flex;
  margin-bottom: 10rpx;
  
  .label {
    width: 120rpx;
    font-size: 28rpx;
    color: #666;
  }
  
  .value {
    flex: 1;
    font-size: 28rpx;
    color: #333;
  }
}

.record-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 20rpx;
  border-top: 1rpx solid #f0f0f0;
  
  .time {
    font-size: 24rpx;
    color: #999;
  }
  
  .action-buttons {
    display: flex;
    gap: 20rpx;
  }
}

.qrcode-popup {
  padding: 30rpx;
  
  .popup-title {
    font-size: 36rpx;
    font-weight: bold;
    text-align: center;
    margin-bottom: 30rpx;
  }
  
  .qrcode-wrapper {
    display: flex;
    justify-content: center;
    margin-bottom: 30rpx;
    
    .qrcode {
      width: 300rpx;
      height: 300rpx;
    }
  }
  
  .popup-info {
    margin-bottom: 30rpx;
  }
  
  .info-item {
    display: flex;
    margin-bottom: 10rpx;
    
    .label {
      width: 120rpx;
      font-size: 28rpx;
      color: #666;
    }
    
    .value {
      flex: 1;
      font-size: 28rpx;
      color: #333;
    }
  }
  
  .popup-tip {
    font-size: 28rpx;
    color: #ff4d4f;
    text-align: center;
    margin-bottom: 30rpx;
  }
  
  .popup-buttons {
    display: flex;
    justify-content: center;
  }
}
</style>
